<?php

if ( get_magic_quotes_gpc() ) {
    $_POST      = array_map( 'stripslashes_deep', $_POST );
}

if(isset($GLOBALS['amazon_sch_search'])){

 	$importcounter =0;
	$emailString="";
    $obj = new AmazonProductAPI();
    
    try
    {
        $result = $obj->searchProducts($_POST['amazon']['keyword'],$_POST['amazon']['keyword_cat'],$_POST['amazon']);		
		//$result = $obj->getItemByKeyword("dvd player","All");
    }
    catch(Exception $e)
    {
       // echo $e->getMessage();
		//exit();
		// no more results
		update_option("schedule_".$a, "");
    }

	$count=0;
	 foreach($result->Items->Item as $val){	 
	$data['title'] 		= $val->ItemAttributes->Title;
	$data['asin'] 		= $val->ASIN;
	$data['url'] 		= $val->DetailPageURL;
 
	if($_POST['amazon']['country'] =="co.uk" || $_POST['amazon']['country'] =="jp"){	
		$data['price'] 	=  substr($val->ItemAttributes->ListPrice->FormattedPrice,2,10);
		if( $data['price'] =="" ){
			$data['price'] 		= substr($val->OfferSummary->LowestNewPrice->FormattedPrice,2,10);
		}
	}elseif($_POST['amazon']['country'] =="de" || $_POST['amazon']['country'] =="fr"){
		$data['price'] 	=  substr($val->OfferSummary->LowestNewPrice->FormattedPrice,4,10);
	}elseif($_POST['amazon']['country'] =="ca"){
		$data['price'] 	=  substr($val->OfferSummary->LowestNewPrice->FormattedPrice,5,10);
	}else{	
		if( isset($val->OfferSummary->LowestNewPrice->Amount) ){	
		$data['price'] 		= substr($val->OfferSummary->LowestNewPrice->FormattedPrice,1,10);
		$data['old_price'] 	=  substr($val->ItemAttributes->ListPrice->FormattedPrice,1,10);
		}else{
		$data['price'] 	=  substr($val->ItemAttributes->ListPrice->FormattedPrice,1,10);
		}
	}
	$data['qty']		= $val->ItemAttributes->NumberOfItems;
	$data['desc']		= $val->EditorialReviews->EditorialReview->Content;
	$data['image'] 		= $val->LargeImage->URL;
	$data['thumbnail']	= $val->MediumImage->URL;
	$data['images'] ="";
	$data['warranty']	= $val->ItemAttributes->Warranty;
	// IMAGE SETS	
	if(isset($val->ImageSets->ImageSet)){
		foreach($val->ImageSets->ImageSet as $img){
			$data['images'] .= $img->MediumImage->URL.",";
		}
	}
	// GET PRODUCT FEATURES
	$excerpt="<ul>";
	foreach($val->ItemAttributes->Feature as $feature){
	$excerpt .="<li>".$feature."</li>";
	}
	$excerpt.="</ul>";
	//	GET ATTRIBUTES
	$extra_data = "<ul class=ExtraData>";
	foreach($val->ItemAttributes as $at1){foreach($at1 as $key => $att){
	$extra_data .= "<li><b>".$key."</b> :";
		if(is_array($att)){
			foreach($att as $in){
				$extra_data .= $in;
			}
		}else{
			$extra_data .= $att;
		}
	$extra_data .= "</li>";
	}}

	$extra_data .="</ul>";

	// SWITCH VALUES IF EMPTY	
	if(strlen($excerpt) < 10){ $excerpt = $extra_data; $extra_data=""; }


	$cc = explode("/",str_replace("http://www.amazon.".$_POST['amazon']['country']."/","",$val->DetailPageURL));
	$data['nicename'] =$cc[0];

	if($_POST['amazon_ID'] ==""){ $_POST['amazon_ID'] ="YOURUSERID"; }


	$AFFLINK = "http://www.amazon.".$_POST['amazon']['country']."/o/ASIN/%asin%/%amazon_id%";
	$AFFLINK = str_replace("%asin%",$data['asin'],$AFFLINK);
	$AFFLINK = str_replace("%amazon_id%",$_POST['amazon_ID'],$AFFLINK);
 
	// CHECK THIS PRODUCT DOESNT ALREADY EXIST		
	$result = mysql_query("SELECT count($wpdb->posts.ID) AS total FROM $wpdb->posts
	INNER JOIN $wpdb->postmeta ON
	($wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_value='".$data['asin']."')
	LIMIT 1", $wpdb->dbh) or die(mysql_error().' on line: '.__LINE__);
			
	$array = mysql_fetch_assoc($result);
		 
	if ($array['total'] ==0 && $data['price'] > 0 && strlen($data['title']) > 3 ) {

			if(strlen($excerpt) < 10){ $excerpt = $extra_data; }		
			
			$data['desc'] 	= str_replace(":"," : ",$data['desc']);
			$excerpt 		= str_replace(":"," : ",$excerpt);
			 
			$my_post = array();
			$my_post['post_title'] 		= $data['title'];
			$my_post['post_content'] 	= $data['desc'];
			$my_post['post_excerpt'] 	= $excerpt;
			$my_post['post_author'] 	= 1;
			$my_post['post_status'] 	= "publish";
			$my_post['post_category'] 	= $_POST['amazon']['cat'];
			$my_post['tags_input'] = str_replace(" ",",",str_replace("-","",str_replace("/","",str_replace("&","",$data['title']))));
			$POSTID = wp_insert_post( $my_post );	  
			  
			$data['price'] 		= str_replace(",","",$data['price']);
			$data['old_price']  = str_replace(",","",$data['old_price']);
			  
			// EXTRA FIELDS
			add_post_meta($POSTID, "amazon_link", $AFFLINK);
			add_post_meta($POSTID, "amazon_guid", $data['asin']);
			add_post_meta($POSTID, "price", $data['price']);
			if(isset($data['old_price']) && strlen($data['old_price']) > 1){ add_post_meta($POSTID, "old_price", $data['old_price']); }
			add_post_meta($POSTID, "warranty", $data['warranty']);
			  
			add_post_meta($POSTID, "image", $data['image']);
			add_post_meta($POSTID, "images", $data['images']);	  
			add_post_meta($POSTID, "qty", 1);	

			$importcounter++;
			$emailString .= "Product ".$importcounter.": ".$data['title']." \n\n";
			  
			  
			// CHECK FOR COMMENTS	  
			$time = current_time('mysql', $gmt = 0);	
				
			  if(isset($val->CustomerReviews->Review)){ foreach($val->CustomerReviews->Review as $review){
		
				$data = array(
					'comment_post_ID' => $POSTID,
					'comment_author' => $review->Reviewer->Name,
					'comment_author_email' => 'admin@admin.com',
					'comment_author_url' => 'http://',
					'comment_content' => nl2br($review->Content),
					//'comment_type' => ,
					'comment_parent' => 0,
					'user_ID' => 1,
					'comment_author_IP' => '127.0.0.1',
					'comment_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)',
					'comment_date' => $review->Date,
					'comment_date_gmt' => $time,
					'comment_approved' => 1,
				);
				
				wp_insert_comment($data);
				
			  } }
 
	}

  }
}

?>